package com.yanxiaohui.config.user;


import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @Description TODO
 * @Author： yanxh<br>
 * @Date 2019/11/14 14:48<br>
 * @Version 1.0<br>
 */
@Configuration
@MapperScan(basePackages = "com.yanxiaohui.user", sqlSessionTemplateRef = "userSqlSessionTemplate")
public class UserMybatisConfig {
    /**
     * @Description 将数据源交给全局的xa事务管理器
     * @Author： yanxh<br>
     * @Date 2019/11/13 17:37<br>
     * @Version 1.0<br>
     */
    @Bean(name = "userDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.user")
    public DataSource userDataSource(){
        return DataSourceBuilder.create().build();
    }


    @Bean(name = "userSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactoryBean(@Qualifier("userDataSource") DataSource dataSource) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        return bean.getObject();

    }


    @Bean(name = "userSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(@Qualifier("userSqlSessionFactory")SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(name = "userTransactionManager")
    public DataSourceTransactionManager sqlSessionTemplate(@Qualifier("userDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}
